class DocumentsController < ApplicationController
  skip_before_filter :authorize, :only => ['new', 'create']

  def index
    @documents = Document.paginate :order => 'created_at DESC', :page => params[:page]
  end

  def show
    @document = Document.find params[:id]
  end

  def new
    @document = Document.new
    render "new", :layout => 'interface'
  end

  def edit
    @document = Document.find params[:id]
  end

  def create
    if params[:revision].blank?
      flash[:error] = '上传文稿选择不正确，请重试'
      redirect_to :action => 'new', :layout => 'interface'
    else
      @document = Document.new params[:document]
      @document.image = Asset.create(params[:image])
      if @document.save
        @revision = Revision.new
        @revision.document_id = @document.id
        @revision.asset = Asset.create(params[:revision])
        @revision.save
        render 'created_successful', :layout => 'interface'
      else
        render :action => 'new', :layout => 'interface'
      end
    end
  end

  def update
    @document = Document.find params[:id]
    if @document.update_attributes params[:document]
      flash.now[:notice] = '更新成功'
      redirect_to @document
    else
      render :action => 'edit'
    end
  end

  def destroy
    @document = Document.find params[:id]
    @document.destroy
    redirect_to documents_path
  end
end
